<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="box">
        <label><input type="checkbox" name="d">游戏<br></label>
        <label><input type="checkbox" name="d">洗浴<br></label>
        <label><input type="checkbox" name="d">按摩<br></label>
        <label><input type="checkbox" name="d">吃饭<br></label>
    </div>
    
    <label><input type="checkbox" name="">
        <input type="checkbox" id="qx" onchange="fn()">全选<br></label>
    <button id="bt1" onclick="fnn()">反选</button>
    <script>
        // var a=document.getElementById('qx').previousElementSibling;
        // console.log(a);
        // 逐个选中后全选被选中
        window.onload = function () {
            document.getElementById('box').onchange = function () {
                var s = document.querySelectorAll('#box input')
                var ss = true
                for (var i = 0; i < s.length; i++) {
                    if (s[i].checked == false) {
                        ss = false;
                        break;
                    } 
                }
                qx.checked = ss
            }
        }
        // 全选
        function fn() {
            var a = document.getElementsByName('d');
            for (var i = 0; i < a.length; i++) {
                if (qx.checked == true) {
                    a[i].checked = true
                } else {
                    a[i].checked = false
                }
            }
        }
        
        // 给每一个选框加事件（不采取）
        function dj() {
            var a = document.getElementsByName('d');
            var te = true;
            for (var i = 0; i < a.length; i++) {
                if (a[i].checked == false) {
                    te = false;
                    break;
                }
            }
            qx.checked = te
        }

        // 反选
        function fnn() {
            var zt = document.getElementsByName('d');
            for (var i = 0; i < zt.length; i++) {
                if (zt[i].checked == true) {
                    zt[i].checked = false
                } else if (zt[i].checked == false) {
                    zt[i].checked = true
                }
            }
        }
    </script>



</body>

</html>